<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('资产编号')" prop="assetNumber">
            <el-input v-model="form.assetNumber" :placeholder="$t('资产编号')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('采购日期')" prop="assetTime">
            <el-date-picker
              v-model="form.assetTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('采购日期')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('资产名称')" prop="assetName">
            <el-input v-model="form.assetName" :placeholder="$t('资产名称')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('规格型号')" prop="assetModel">
            <el-input v-model="form.assetModel" :placeholder="$t('规格型号')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('序列号')" prop="serialNumber">
            <el-input v-model="form.serialNumber" :placeholder="$t('序列号')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('数量')" prop="assetCount">
            <el-input-number v-model="form.assetCount" :placeholder="$t('数量')" maxlength="25" :min="1" @input="calcTotal" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('单价')+ $t('(元)')" prop="assetPrice">
            <Money v-model="form.assetPrice" :placeholder="$t('单价')" @change="calcTotal" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('金额')+ $t('(元)')" prop="assetAmount">
            <Money v-model="form.assetAmount" :placeholder="$t('金额')" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('资产状态')" prop="assetState">
            <dict-select
              v-model="form.assetState"
              dictionary="asset_state"
              :placeholder="$t('资产状态')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('存放地点')" prop="storageLocation">
            <el-input v-model="form.storageLocation" :placeholder="$t('存放地点')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('所属公司')" prop="company">
            <el-input v-model="form.company" :placeholder="$t('所属公司')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="area-header">
        <span class="area-header-title">{{ $t('使用记录') }}</span>
      </div>
      <el-table
        :data="form.oaAssetsRecordList"
        border
        class="nowrapTable formTable"
      >
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('使用人')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('使用人') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaAssetsRecordList.' + scope.$index + '.user' " :rules="RecordListRules.user">
              <UserSelect v-model="scope.row.user" :placeholder="$t('使用人')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('使用部门')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('使用部门') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaAssetsRecordList.' + scope.$index + '.department' " :rules="RecordListRules.department">
              <DeptSelect v-model="scope.row.department" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('使用日期')" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="'oaAssetsRecordList.' + scope.$index + '.recordDate' ">
              <el-date-picker
                v-model="scope.row.recordDate"
                clearable
                style="width: 200px"
                type="date"
                value-format="yyyy-MM-dd"
                :placeholder="$t('使用日期')"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('使用状态')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('使用状态') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaAssetsRecordList.' + scope.$index + '.recordState' " :rules="RecordListRules.recordState">
              <el-select
                v-model="scope.row.recordState"
                :placeholder="$t('请选择')"
              >
                <el-option
                  v-for="dict in recordStateOptions"
                  :key="dict.dictValue"
                  :label="$t(dict.dictLabel)"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('归还日期')" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="'oaAssetsRecordList.' + scope.$index + '.returnDate'">
              <el-date-picker
                v-model="scope.row.returnDate"
                clearable
                style="width: 200px"
                type="date"
                value-format="yyyy-MM-dd"
                :placeholder="$t('归还日期')"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" align="center" width="80">
          <template slot-scope="scope">
            <el-button v-hasPermi="['oa:assets:remove']" size="small" type="text" icon="el-icon-delete" @click="delHandle(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div class="tol">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addRecord">{{ $t("添加") }}</el-button>
      </div>
      <FileTable :list.sync="form.fileList" data-type="oa_assets" :business-id="autoBusinessId($route.query.id, form)" class="list-table" :btn-show="!otherBtnHide" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn has-permi="oa:assets" />
    </div>
  </div>
</template>
<script>
    import { saveOaAssets, getOaAssets, deleteAssetsRecord } from '@/api/oa/assets/oaAssets'
    import { getUser } from '@/api/system/user'
    export default {
        data() {
            return {
              otherBtnHide: false,
              // 资产状态字典
              assetStateOptions: [],
              // 使用状态字典
              recordStateOptions: [],
                // 表单参数
                form: {
                  // 上传
                  fileList: [],
                  // 使用记录
                  oaAssetsRecordList: []
                },
                // 遮罩层
                loading: false,
                // 表单校验
                rules: {
                assetNumber: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                assetName: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                assetCount: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                assetAmount: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                assetState: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ]
                },
              RecordListRules: {
                user: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                department: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                recordState: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
              }
            }
        },
      watch: {
        'row.user': {
          handler(val) {
            if (val !== undefined && val !== null && val !== '') { this.userInfo(val) }
          },
          deep: true,
          immediate: true
        }
      },
      mounted() {
        this.$bus.$emit('async_done')
      },
        created() {
            this.getDicts('asset_state').then(response => {
                this.assetStateOptions = response.data
            })
              this.getDicts('record_state').then(response => {
                this.recordStateOptions = response.data
              })
        },
        methods: {
          handleChange(value) {
            console.log(value)
          },
            // 初始化数据
          init(data) {
            this.loading = true
            if (data != null && data.id !== undefined) {
              getOaAssets(data.id).then(response => {
                if (response.data != null) {
                  this.form = response.data
                  if (this.form.assetCount) {
                    this.form.assetCount = Number(this.form.assetCount)
                  }
                  if (this.form.assetPrice) {
                    this.form.assetPrice = Number(this.form.assetPrice)
                  }
                  if (this.form.assetAmount) {
                    this.form.assetAmount = Number(this.form.assetAmount)
                  }
                } else {
                  this.reset()
                }
                this.loading = false
              })
            } else {
              this.reset()
              this.loading = false
            }
          },
          // 根据选择的用户不同显示部门
          userInfo(userId) {
            getUser(userId).then(response => {
              this.form.department = response.data.department
            })
          },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,

                    department: undefined,
                    user: undefined,

                    assetNumber: undefined,

                    assetTime: undefined,

                    assetName: undefined,

                    assetModel: undefined,

                    assetCount: 1,

                    assetPrice: undefined,

                    assetAmount: undefined,

                    assetState: undefined,

                    storageLocation: undefined,

                    company: undefined,

                    serialNumber: undefined,

                    remark: undefined,

                    delFlag: undefined,

                    createBy: undefined,

                    createTime: undefined,

                    updateBy: undefined,

                    updateTime: undefined,

                    oaAssetsRecordList: []

                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 计算金额
          calcTotal() {
            var count = this.form.assetCount ? Number(this.form.assetCount) : 0
            var amount = this.form.assetPrice ? Number(this.form.assetPrice) : 0
            this.form.assetAmount = Number((count * amount).toFixed(2))
          },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                  this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
            },
            /** 提交按钮 */
            submitForm: function() {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.loading = true
                        saveOaAssets(this.form).then(response => {
                            if (response.code === 200) {
                                this.form.id = response.data.id
                                this.msgSuccess(this.$t('保存成功'))
                                this.closeForm()
                            } else {
                                this.msgError(response.msg)
                            }
                            this.loading = false
                        })
                    } else {
                       this.locationError(document)
                    }
                })
           },
          // 添加使用记录
          addRecord() {
            const row = {
              id: undefined,
              assetsId: undefined,
              user: undefined,
              department: undefined,
              recordDate: undefined,
              recordState: '',
              returnDate: undefined
            }
            if (!(this.form.oaAssetsRecordList instanceof Array)) {
              this.$set(this.form, 'oaAssetsRecordList', [])
            }
            this.$nextTick(() => {
              this.form.oaAssetsRecordList.push(row)
            })
          },
          // 删除使用记录
          delHandle(index, row) {
            const id = row.id
            if (id !== undefined && id !== '' && id != null) {
              this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
              })
                .then(function() {
                  return deleteAssetsRecord(id)
                }).then(() => {
                this.form.oaAssetsRecordList.splice(index, 1)
                return this.msgSuccess(this.$t('删除成功'))
              })
                .catch(function() {})
            } else {
              this.form.oaAssetsRecordList.splice(index, 1)
            }
          }
        }
    }
</script>
